package com.hollycrm.util;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

/**
 * Created by aber on 2017/2/27.
 */

public class RC4Utils {

    public static final String KEY = "hollycrm";

    public static final String ALGORITHM = "RC4";

    public static byte[] encrypt(byte[] toEncrypt) throws Exception{
        SecureRandom sr = new SecureRandom(KEY.getBytes("UTF-8"));
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
        kg.init(sr);
        SecretKey sk = kg.generateKey();

        Cipher cipher = Cipher.getInstance(ALGORITHM);

        cipher.init(Cipher.ENCRYPT_MODE,sk);

        byte[]  encrypted = cipher.doFinal(toEncrypt);
        return encrypted;
    }

    public static byte[] decrypt(byte[] decrypt) throws Exception{
        // create a binary key from the argument key (seed)
        SecureRandom sr = new SecureRandom(KEY.getBytes("UTF-8"));
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
        kg.init(sr);
        SecretKey sk = kg.generateKey();

        // do the decryption with that key
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, sk);
        byte[] decrypted = cipher.doFinal(decrypt);

        return decrypted;
    }
}
